package com.sjg.sys.quartz;

import com.sjg.sys.entity.SysScheduleJob;
import com.sjg.sys.service.SysScheduleJobService;
import org.quartz.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class QuartzJobManage implements InitializingBean {

    @Resource
    private Scheduler scheduler;
    @Resource
    private SysScheduleJobService sysScheduleJobService;

    private static Boolean isinit=false;
    /**
     * 初始化定时任务
     * @throws SchedulerException
     */
    public void initTask() throws SchedulerException {
        System.err.println(scheduler);
        // 这里获取任务信息数据
//        List<SysScheduleJob> jobList = sysScheduleJobService.select(new SysScheduleJob());//从数据库中读取
//        for (SysScheduleJob job : jobList) {
//            addJob(job);
//        }
    }
    /**
     * 添加一个任务
     * @param job
     */
    public void addOrUpdateJob(SysScheduleJob job){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
            // 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 不存在，创建一个
            if (null == trigger) {
                JobDetail jobDetail = JobBuilder.newJob(QuartzJobTemplate.class)
                        .withIdentity(job.getJobName(), job.getJobGroup()).build();
                jobDetail.getJobDataMap().put("scheduleJob", job);
                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
                // 按新的cronExpression表达式构建一个新的trigger
                trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
                        .withSchedule(scheduleBuilder).build();
                scheduler.scheduleJob(jobDetail, trigger);
            } else {
                // Trigger已存在，那么更新相应的定时设置
                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
            }
            if(job.getJobStatus()!=null&&job.getJobStatus().intValue()==1){
                pauseJob(job);
            }

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 暂停一个job
     * @param scheduleJob
     * @throws SchedulerException
     */
    public void pauseJob(SysScheduleJob scheduleJob){
        //Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 恢复一个job
     * @param scheduleJob
     */
    public void resumeJob(SysScheduleJob scheduleJob){
        //Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(),scheduleJob.getJobGroup());
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除一个任务
     */
    public void removeJob(SysScheduleJob job){
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        JobKey jobKey = JobKey.jobKey(job.getJobName(),job.getJobGroup());
        // 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
        //CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        try {
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //这样做仍然没有用需要缓存起来做判断
        if(!isinit){

            System.out.println(scheduler);
        }
        // 这里获取任务信息数据
//        List<SysScheduleJob> jobList = sysScheduleJobService.select(new SysScheduleJob());//从数据库中读取
//        for (SysScheduleJob job : jobList) {
//            addJob(job);
//        }
        isinit=true;
    }
}
